﻿using Autofac;
using AutoMapper;
using System;
using System.Linq;
using System.Reflection;
using Yz.Cache;
using Yz.Core.Base;
using Yz.DataAccess.ModelMapper;

namespace Yz.WinService.Hangfire
{
    public class AutofacBuilder
    {
        private static IContainer _container;
        public static void Init()
        {
            var builder = new ContainerBuilder();

            #region 实现接口IDependency 的自动注入
            var baseType = typeof(IDependency);
            var assemblys = AppDomain.CurrentDomain.GetAssemblies().ToList();
            string path = AppDomain.CurrentDomain.BaseDirectory;
            var assemblys1 = Assembly.LoadFrom(path + "Yz.DataAccess.dll");
            assemblys.Add(assemblys1);
            builder.RegisterAssemblyTypes(assemblys.ToArray())
                  .Where(t => baseType.IsAssignableFrom(t) && t != baseType)
                  .PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies).AsImplementedInterfaces().InstancePerLifetimeScope();
            #endregion

            #region 缓存注入 (手动注入) 
            builder.RegisterType<CacheRedisUitility>()
          .PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies).As<ICacheUitility>()
          .InstancePerLifetimeScope();
            #endregion

            #region 当前的服务注入
            builder.RegisterType<YzHfService>()
              .PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies).As<YzHfService>()
              .InstancePerLifetimeScope();
            #endregion 

            #region autoMapper注入 
            builder.RegisterType<Mapper>()
            .PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies).As<IMapper>()
            .InstancePerLifetimeScope();
            #endregion

            builder.Register<IConfigurationProvider>(ctx => new MapperConfiguration(x =>
            {
                x.AddProfile<SourceProfileApi>();
                x.AddProfile<SourceProfileVm>();
            })).PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies).InstancePerLifetimeScope();
            _container = builder.Build();
        }
        public static T GetFromFac<T>()
        {
            return _container.Resolve<T>();
        }
    }
}
